package cn.shujuhai.qtadmin.platform.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import cn.hutool.core.util.ObjectUtil;
import cn.shujuhai.qtadmin.platform.domain.SysMenu;
import cn.shujuhai.qtadmin.platform.domain.SysUser;
import cn.shujuhai.qtadmin.platform.kit.SecurityUtil;
import cn.shujuhai.qtadmin.platform.mapper.SysMenuMapper;
import cn.shujuhai.qtadmin.platform.service.SysMenuService;
import lombok.SneakyThrows;

/**
 * @author dch
 */
@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    /**
     *
     * @param menuInfo
     *            menuInfoList
     * @return userMeunMap
     */
    private @NotNull Map<String, Object> getUserMenus(List<SysMenu> menuInfo) {
        Map<String, Object> map = new HashMap<>(16);
        Map<String, Object> home = new HashMap<>(16);
        home.put("title", "首页");
        home.put("href", "/welcome");
        Map<String, Object> logo = new HashMap<>(16);
        logo.put("title", "QT_Admin");
        logo.put("image", "/lib/layuimini/images/logo.png");
        logo.put("href", "/index");
        map.put("menuInfo", menuInfo);
        map.put("logoInfo", logo);
        map.put("homeInfo", home);
        return map;
    }

    /**
     *
     * @return userMenu
     */
    @SneakyThrows
    @Override
    public Map<String, Object> getMenus4user() {
        SysUser user = (SysUser)SecurityUtil.currentUserObj();
        var menuList = this.baseMapper.getMenus4user(user.getId());
        var patternMenu = menuList.stream().filter(s -> s.getParentId() == 0).collect(Collectors.toList());
        patternMenu.forEach(s -> s.setChild(this.getChildrenMenus(s.getId(), menuList)));
        return this.getUserMenus(patternMenu);
    }

    /**
     *
     * @param id
     *            id
     * @param allMenus
     *            allMenus
     * @return userMenus
     */
    private List<SysMenu> getChildrenMenus(Long id, @NotNull List<SysMenu> allMenus) {
        var childrens = allMenus.stream().filter(s -> s.getParentId().equals(id)).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(childrens)) {
            childrens.forEach(x -> this.getChildrenMenus(x.getId(), allMenus));
        }
        return childrens;
    }
}
